<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>学生管理</span>
        <div class="header-actions">
          <el-button type="primary" @click="handleAdd">新增学生</el-button>
          <el-button @click="handleRefresh">刷新</el-button>
          <el-button @click="handleExportStudents">导出学生</el-button>
          <el-button @click="previewStudentTemplate">下载模板</el-button>
          <el-button @click="importStudents">导入学生</el-button>
        </div>
      </div>
    </template>

    <!-- 搜索条件 -->
    <el-form :model="searchForm" label-width="80px" class="search-form">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="学号">
            <el-input v-model="searchForm.studentId" placeholder="请输入学号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="姓名">
            <el-input v-model="searchForm.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 学生列表 -->
    <el-table :data="studentList" border style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="studentNo" label="学号" width="120" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="collegeName" label="学院" width="150" />
      <el-table-column prop="majorName" label="专业" width="150" />
      <el-table-column prop="className" label="班级" width="150" />
      <el-table-column prop="enrollmentYear" label="入学年份" width="120" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="pagination"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="学号" prop="studentNo">
          <el-input v-model="form.studentNo" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="学院" prop="collegeId">
          <el-select v-model="form.collegeId" placeholder="请选择学院" style="width: 100%" @change="handleCollegeChange">
            <el-option
              v-for="college in collegeOptions"
              :key="college.id"
              :label="college.name"
              :value="college.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="majorId">
          <el-select v-model="form.majorId" placeholder="请选择专业" style="width: 100%" @change="handleMajorChange">
            <el-option
              v-for="major in majorOptions"
              :key="major.id"
              :label="major.name"
              :value="major.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="form.classId" placeholder="请选择班级" style="width: 100%">
            <el-option
              v-for="classItem in classOptions"
              :key="classItem.id"
              :label="classItem.name"
              :value="classItem.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入学年份" prop="enrollmentYear">
          <el-date-picker
            v-model="form.enrollmentYear"
            type="year"
            placeholder="选择入学年份"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 导入对话框 -->
    <el-dialog v-model="importDialogVisible" title="导入学生数据" width="500px">
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        action="http://localhost:8080/api/students/import"
        :auto-upload="false"
        :on-change="handleFileChange"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
      >
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        <el-button class="ml-3" type="success" @click="submitUpload" :loading="uploadLoading">
          上传到服务器
        </el-button>
        <template #tip>
          <div class="el-upload__tip">
            请上传Excel文件 (.xlsx)，下载模板请点上方"下载模板"按钮
          </div>
        </template>
      </el-upload>
    </el-dialog>
    
    <!-- 学生模板预览对话框 -->
    <el-dialog v-model="templatePreviewVisible" title="学生导入模板预览" width="800px">
      <el-table :data="templatePreviewData" border style="width: 100%">
        <el-table-column prop="studentNo" label="学号" width="120" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="collegeName" label="学院" width="150" />
        <el-table-column prop="majorName" label="专业" width="150" />
        <el-table-column prop="className" label="班级" width="150" />
        <el-table-column prop="enrollmentYear" label="入学年份" width="120" />
      </el-table>
      <div class="template-preview-footer">
        <p>以上为学生导入模板的结构示例，请按照此格式填写数据</p>
        <el-button type="primary" @click="downloadStudentTemplate">下载模板文件</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  studentId: '',
  name: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 学生列表
const studentList = ref([])

const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 导入相关
const importDialogVisible = ref(false)
const uploadRef = ref()
const uploadLoading = ref(false)
const selectedFile = ref(null)

// 模板预览相关
const templatePreviewVisible = ref(false)
const templatePreviewData = ref([
  {
    studentNo: '2022001',
    name: '张三',
    collegeName: '软件学院',
    majorName: '软件工程',
    className: '软件工程2022级1班',
    enrollmentYear: '2022'
  }
])

// 下拉选项数据
const collegeOptions = ref([])
const majorOptions = ref([])
const classOptions = ref([])

// 表单数据
const form = reactive({
  id: '',
  userId: '',
  studentNo: '',
  name: '',
  collegeId: '',
  majorId: '',
  classId: '',
  enrollmentYear: ''
})

// 表单验证规则
const rules = {
  studentNo: [{ required: true, message: '请输入学号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  enrollmentYear: [{ required: true, message: '请选择入学年份', trigger: 'change' }]
}

const formRef = ref()

// 格式化日期显示
const formatDate = (dateString) => {
  if (!dateString) return ''
  // 如果是Date对象，直接格式化
  if (dateString instanceof Date) {
    return dateString.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    }).replace(/\//g, '-')
  }
  
  // 如果是字符串，先转换为Date对象
  const date = new Date(dateString)
  if (isNaN(date.getTime())) return '' // 无效日期返回空字符串
  
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
}

// 获取学生列表
const fetchStudents = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = new URLSearchParams();
    if (searchForm.studentId) {
      params.append('studentNo', searchForm.studentId);
    }
    if (searchForm.name) {
      params.append('name', searchForm.name);
    }
    
    // 添加分页参数
    params.append('page', pagination.currentPage - 1); // 后端分页从0开始
    params.append('size', pagination.pageSize);
    
    const url = `http://localhost:8080/api/students?${params.toString()}`;
    
    const response = await axios.get(url);
    studentList.value = response.data.content.map(student => ({
      ...student,
      createTime: formatDate(student.createdAt)
    }));
    pagination.total = response.data.totalElements;
  } catch (error) {
    console.error('获取学生列表失败:', error);
    ElMessage.error('获取学生列表失败');
  } finally {
    loading.value = false;
  }
}

// 获取学院列表
const fetchColleges = async () => {
  try {
    // 添加分页参数，获取所有学院
    const params = new URLSearchParams();
    params.append('page', 0); // 获取第一页
    params.append('size', 1000); // 设置一个较大的页面大小以获取所有学院
    
    const response = await axios.get(`http://localhost:8080/api/colleges?${params.toString()}`);
    // 处理分页响应数据
    collegeOptions.value = response.data.content || response.data;
  } catch (error) {
    console.error('获取学院列表失败:', error);
    ElMessage.error('获取学院列表失败');
  }
}

// 根据学院ID获取专业列表
const fetchMajorsByCollegeId = async (collegeId) => {
  try {
    const response = await axios.get(`http://localhost:8080/api/majors/college/${collegeId}`);
    majorOptions.value = response.data;
  } catch (error) {
    console.error('获取专业列表失败:', error);
    ElMessage.error('获取专业列表失败');
  }
}

// 根据专业ID获取班级列表
const fetchClassesByMajorId = async (majorId) => {
  try {
    const response = await axios.get(`http://localhost:8080/api/classes/major/${majorId}`);
    classOptions.value = response.data;
  } catch (error) {
    console.error('获取班级列表失败:', error);
    ElMessage.error('获取班级列表失败');
  }
}

// 获取所有专业列表
const fetchMajors = async () => {
  try {
    // 添加分页参数，获取所有专业
    const params = new URLSearchParams();
    params.append('page', 0); // 获取第一页
    params.append('size', 1000); // 设置一个较大的页面大小以获取所有专业
    
    const response = await axios.get(`http://localhost:8080/api/majors?${params.toString()}`);
    // 处理分页响应数据
    majorOptions.value = response.data.content || response.data;
  } catch (error) {
    console.error('获取专业列表失败:', error);
    ElMessage.error('获取专业列表失败');
  }
}

// 获取所有班级列表
const fetchClasses = async () => {
  try {
    // 添加分页参数，获取所有班级
    const params = new URLSearchParams();
    params.append('page', 0); // 获取第一页
    params.append('size', 1000); // 设置一个较大的页面大小以获取所有班级
    
    const response = await axios.get(`http://localhost:8080/api/classes?${params.toString()}`);
    // 处理分页响应数据
    classOptions.value = response.data.content || response.data;
  } catch (error) {
    console.error('获取班级列表失败:', error);
    ElMessage.error('获取班级列表失败');
  }
}

// 当学院选择改变时
const handleCollegeChange = (collegeId) => {
  // 清空专业和班级的选择
  form.majorId = '';
  form.classId = '';
  majorOptions.value = [];
  classOptions.value = [];
  
  // 如果选择了学院，则加载该学院下的专业
  if (collegeId) {
    fetchMajorsByCollegeId(collegeId);
  }
}

// 当专业选择改变时
const handleMajorChange = (majorId) => {
  // 清空班级的选择
  form.classId = '';
  classOptions.value = [];
  
  // 如果选择了专业，则加载该专业下的班级
  if (majorId) {
    fetchClassesByMajorId(majorId);
  }
}

// 搜索
const handleSearch = async () => {
  console.log('搜索:', searchForm)
  await fetchStudents()
}

// 重置
const handleReset = () => {
  searchForm.studentId = ''
  searchForm.name = ''
  fetchStudents()
}

// 刷新
const handleRefresh = () => {
  fetchStudents()
}

// 预览学生模板
const previewStudentTemplate = () => {
  templatePreviewVisible.value = true;
}

// 下载学生模板
const downloadStudentTemplate = async () => {
  try {
    const response = await axios.get('http://localhost:8080/api/students/template', {
      responseType: 'blob'
    });
    
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '学生导入模板.xlsx');
    document.body.appendChild(link);
    link.click();
    
    // 清理
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    
    ElMessage.success('模板下载成功');
    templatePreviewVisible.value = false;
  } catch (error) {
    console.error('下载模板失败:', error);
    ElMessage.error('下载模板失败');
  }
}

// 导入学生
const importStudents = () => {
  importDialogVisible.value = true;
}

// 处理文件选择
const handleFileChange = (file) => {
  selectedFile.value = file.raw;
}

// 提交上传
const submitUpload = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择文件');
    return;
  }
  
  uploadLoading.value = true;
  
  const formData = new FormData();
  formData.append('file', selectedFile.value);
  
  try {
    const response = await axios.post('http://localhost:8080/api/students/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    ElMessage.success(response.data);
    importDialogVisible.value = false;
    fetchStudents(); // 刷新学生列表
  } catch (error) {
    console.error('导入失败:', error);
    ElMessage.error('导入失败: ' + (error.response?.data || error.message));
  } finally {
    uploadLoading.value = false;
  }
}

// 上传成功处理
const handleUploadSuccess = (response, file, fileList) => {
  uploadLoading.value = false;
  ElMessage.success('导入成功');
  importDialogVisible.value = false;
  fetchStudents(); // 刷新学生列表
}

// 上传失败处理
const handleUploadError = (error, file, fileList) => {
  uploadLoading.value = false;
  ElMessage.error('导入失败: ' + error);
}

// 新增
const handleAdd = async () => {
  dialogTitle.value = '新增学生'
  isEdit.value = false
  // 重置表单
  Object.keys(form).forEach(key => {
    form[key] = ''
  })
  dialogVisible.value = true
  // 加载学院下拉选项数据
  await fetchColleges()
}

// 编辑
const handleEdit = async (row) => {
  dialogTitle.value = '编辑学生'
  isEdit.value = true
  // 填充表单数据
  form.id = row.id
  form.userId = row.userId
  form.studentNo = row.studentNo
  form.name = row.name
  form.collegeId = row.collegeId
  form.majorId = row.majorId
  form.classId = row.classId
  form.enrollmentYear = row.enrollmentYear
  dialogVisible.value = true
  // 加载下拉选项数据
  await fetchColleges()
  
  // 如果有学院ID，加载该学院下的专业
  if (row.collegeId) {
    await fetchMajorsByCollegeId(row.collegeId);
  }
  
  // 如果有专业ID，加载该专业下的班级
  // 注意：这里需要确保专业ID对应的确实是当前学院下的专业
  if (row.majorId && row.collegeId) {
    // 验证专业是否属于当前学院
    const isValidMajor = majorOptions.value.some(major => major.id === row.majorId);
    if (isValidMajor) {
      await fetchClassesByMajorId(row.majorId);
    }
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除学生 ${row.name} 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用后端API删除
    await axios.delete(`http://localhost:8080/api/students/${row.id}`)
    ElMessage.success('删除成功')
    fetchStudents() // 重新加载数据
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除学生失败:', error)
      ElMessage.error('删除学生失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 格式化入学年份
        let enrollmentYear = form.enrollmentYear;
        if (enrollmentYear instanceof Date) {
          enrollmentYear = enrollmentYear.getFullYear();
        } else if (typeof enrollmentYear === 'string') {
          enrollmentYear = parseInt(enrollmentYear, 10);
        }
        
        if (isEdit.value) {
          // 编辑操作 - 直接更新学生信息
          const studentData = {
            userId: form.userId,
            studentNo: form.studentNo,
            collegeId: form.collegeId,
            majorId: form.majorId,
            classId: form.classId,
            enrollmentYear: enrollmentYear
          };
          
          // 同时更新用户表中的姓名信息
          const userData = {
            realName: form.name
          };
          
          // 并行更新学生和用户信息
          await Promise.all([
            axios.put(`http://localhost:8080/api/students/${form.id}`, studentData),
            axios.put(`http://localhost:8080/api/users/${form.userId}`, userData)
          ]);
          
          ElMessage.success('编辑成功')
        } else { 
          // 新增操作 - 先创建用户，再创建学生
          // 获取当前时间
          const now = new Date().toISOString();
          
          // 1. 创建用户
          const userData = {
            username: form.studentNo, // 使用学号作为用户名
            realName: form.name,
            gender: '男', // 默认值改为数据库允许的值
            role: 'student',
            status: 'active',
            password: '$2a$10$7JB720yubVSOfvK5j6s0oOjGHOOzn2oLs1yLowJO0aPjJ9zJ5jEAu', // 默认密码123456的哈希值
            createdAt: now,
            updatedAt: now
          };
          
          const userResponse = await axios.post('http://localhost:8080/api/users', userData);
          const userId = userResponse.data.id;
          
          // 2. 创建学生记录
          const studentData = {
            userId: userId,
            studentNo: form.studentNo,
            collegeId: form.collegeId,
            majorId: form.majorId,
            classId: form.classId,
            enrollmentYear: enrollmentYear
          };
          
          await axios.post('http://localhost:8080/api/students', studentData)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        fetchStudents() // 重新加载数据
      } catch (error) {
        console.error('操作失败:', error)
        console.error('Response data:', error.response?.data);
        ElMessage.error('操作失败: ' + (error.response?.data?.message || error.response?.data || error.message))
      }
    }
  })
}

// 分页相关
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchStudents()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchStudents()
}

// 导出学生列表
const handleExportStudents = async () => {
  try {
    // 发起导出请求
    const response = await axios({
      method: 'get',
      url: 'http://localhost:8080/api/students/export',
      responseType: 'blob' // 重要：设置响应类型为blob
    });
    
    // 创建下载链接
    const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = '学生列表.xlsx';
    link.click();
    
    // 清理URL对象
    window.URL.revokeObjectURL(url);
    
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败: ' + (error.response?.data?.message || error.message));
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchStudents()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.template-preview-footer {
  margin-top: 20px;
  text-align: center;
}

.template-preview-footer p {
  margin-bottom: 15px;
  color: #666;
}
</style>